package com.zadtek.jpsqishi.activity;

import java.util.ArrayList;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.zadtek.jpsqishi.R;
import com.zadtek.jpsqishi.activity.adapter.ShopdetAdapter;
import com.zadtek.jpsqishi.activity.common.Common;
import com.zadtek.jpsqishi.activity.common.Const;
import com.zadtek.jpsqishi.activity.data.OrderdetailData;
import com.zadtek.jpsqishi.activity.data.OrderdetailSite;
import com.zadtek.jpsqishi.activity.data.QiangDanData;
import com.zadtek.jpsqishi.frame.JsonProcessHelper;
import com.zadtek.jpsqishi.views.MyListView;

/**
 * 订单详情界面
 *
 * @author Administrator
 */
@EActivity(R.layout.order_detail)
public class OrderDetailActivity extends BaseActivity implements AMapLocationListener {

    @ViewById
    ImageView backid;

    @ViewById
    TextView topview, beizhu, address, ps_address; // 标题,备注、地址

    @ViewById
    LinearLayout beizhulay, address_layout; // 备注面板、地址跳转

    @ViewById
    MyListView listView;

    @ViewById
    TextView order_main, order_psmy, ordpaysta; // 总订单号,总配送费,支付方式
    QiangDanData qiangdan;
    private TextView jiedtime, qhuotime, wanctime; // 备注,发票,接单时间,取货,完成
    private TextView pstimes; // 配送耗时
    private LinearLayout orderwclay; // 配送完成底部的面板

    private LayoutInflater inflater;
    private View bottomview; // 底部面板

    private OrderdetailData detaildata; // 订单详情
    private Handler mHandler;

    private ListAdapter myAdapter;
    private ArrayList<OrderdetailSite> sitelists;

    private SharedPreferences sp; // 用户信息缓存

    private Dialog dialog;
    private int getfoodid = 0; // 取货的下标
    private String Mainid = "";

    private String mStatus;
    private String lat = "0.0", lng = "0.0";
    public AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mlocationClient;
    private boolean shorterThan200 = false;
    private double shopLat = 0, shopLnt = 0;

    // 初始化
    @AfterViews
    void initViews() {
        topview.setText("订单详情");
        inflater = getLayoutInflater();
        bottomview = inflater.inflate(R.layout.order_detail_bottom, null);
        jiedtime = (TextView) bottomview.findViewById(R.id.jiedtime);
        qhuotime = (TextView) bottomview.findViewById(R.id.qhuotime);
        wanctime = (TextView) bottomview.findViewById(R.id.wanctime);
        pstimes = (TextView) bottomview.findViewById(R.id.pstimes);
        orderwclay = (LinearLayout) bottomview.findViewById(R.id.orderwclay);

        listView.addFooterView(bottomview);
    }

    @Click(R.id.backid)
    void backonclik() {
        finish();
    }

    @Click(R.id.address_layout)
    void Addressclick() {
        if (!lat.equals("0.0") && null != lat && !lng.equals("0.0")
                && null != lng && !lat.equals("null") && !lng.equals("null")) {

            Intent intent = new Intent(this, MyMapLocation.class);
            intent.putExtra("lat", lat);
            intent.putExtra("lng", lng);
            startActivity(intent);
        } else {
            Common.DisplayToast(OrderDetailActivity.this, "坐标获取失败！", 2);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null) {
            mStatus = bundle.getString("status");
            Mainid = bundle.getString("mainid");
            dialog = Common.getTipDialog(OrderDetailActivity.this,
                    R.layout.loading, 0, 0);
            new myAsyncTask().execute("getdetail", Mainid);// 201603241436063221
        }
        mlocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        mlocationClient.setLocationListener(this);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setInterval(2000);
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                switch (msg.what) {
                    case Const.STATE_START_SUCCESS: // 成功
                        closeDialog();
                        detaildata = (OrderdetailData) msg.obj;
                        shopLat = Double.parseDouble(detaildata.getSitelist().get(0).getLat());
                        shopLnt = Double.parseDouble(detaildata.getSitelist().get(0).getLng());
                        String status = detaildata.getState();
                        if (status != null && status.equals("1")) {
                            order_main.setText("订单号：" + detaildata.getMain_id());
                            order_psmy.setText("总配送费：" + detaildata.getReturnpay()
                                    + "元");

                            String payvar = "支付宝支付";
                            String paytype = detaildata.getSitelist().get(0)
                                    .getPaytype();
                            if (paytype.equals("0")) {
                                payvar = "货到付款";
                            } else if (paytype.equals("1") || paytype.equals("3")) {
                                payvar = "支付宝支付";
                            } else if (paytype.equals("2")) {
                                payvar = "微信支付";
                            }
                            ordpaysta.setText(payvar);

                            jiedtime.setText(detaildata.getAdd_time());
                            qhuotime.setText(detaildata.getGet_time());
                            wanctime.setText(detaildata.getSend_time());
                            String ordmark = detaildata.getOrder_mark();
                            if (ordmark != null && !ordmark.equals("")) {
                                beizhulay.setVisibility(View.VISIBLE);
                                beizhu.setText(ordmark);
                            } else {
                                beizhulay.setVisibility(View.GONE);
                            }
                            pstimes.setText("配送耗时：" + detaildata.getTimes() + "分钟");
                            sitelists = detaildata.getSitelist();
                            String mainstatus = detaildata.getStatus();
                            if (mainstatus != null && mainstatus.equals("4")) {
                                orderwclay.setVisibility(View.VISIBLE);
                            } else {
                                orderwclay.setVisibility(View.GONE);
                            }
                            if (mStatus.equals("ps")) {
                                try {
                                    String address_road = detaildata.getAddress_road();
                                    String str = detaildata.getSitelist().get(0)
                                            .getPhone_addr();
                                    if (!str.equals("null") && null != str
                                            && !str.equals("") && str.contains(",")) {
                                        String[] st = str.split(",");
                                        lng = st[0];
                                        lat = st[1];
                                        if (address_road == null
                                                || address_road.equals("")
                                                || address_road.equals("null")) {
                                            if (lat != null && !lat.equals("")
                                                    && !lat.equals("null")) {
                                                getAdderss(Double.parseDouble(lat),
                                                        Double.parseDouble(lng));
                                            }
                                        } else {
                                            ps_address.setText(address_road);
                                        }
                                        ps_address.setVisibility(View.VISIBLE);
                                    } else {
                                        ps_address.setVisibility(View.GONE);
                                    }
                                    if (null != detaildata.getSendaddress()
                                            && !detaildata.getSendaddress().equals("")) {
                                        address.setText(detaildata.getSendaddress());
                                    }
                                } catch (Exception e) {
                                }
                            } else if (mStatus.equals("wait")) {
                                try {
                                    if (detaildata.getSitelist().get(0).getLat() != null
                                            && detaildata.getSitelist().get(0)
                                            .getLng() != null
                                            && !detaildata.getSitelist().get(0)
                                            .getLat().equals("")
                                            && !detaildata.getSitelist().get(0)
                                            .getLng().equals("")) {
                                        lat = detaildata.getSitelist().get(0)
                                                .getLat();
                                        lng = detaildata.getSitelist().get(0)
                                                .getLng();
                                    }
                                    ps_address.setVisibility(View.GONE);

                                    if (null != detaildata.getSitelist().get(0)
                                            .getSite_addr()
                                            && !detaildata.getSitelist().get(0)
                                            .getSite_addr().equals("")) {
                                        address.setText(detaildata.getSitelist().get(0)
                                                .getSite_addr());
                                    }
                                } catch (Exception e) {
                                }
                            } else if (mStatus.equals("over")) {
                                address_layout.setVisibility(View.GONE);
                                // address.setText(detaildata.getSitelist().get(0)
                                // .getSite_addr());
                            }

                            myAdapter = new ListAdapter();
                            listView.setAdapter(myAdapter);

                        } else {
                            Common.DisplayToast(OrderDetailActivity.this,
                                    detaildata.getMessage(), 2);
                            finish();
                        }
                        break;
                    case Const.STATE_START_ERROR:
                        closeDialog();
                        Common.DisplayToast(OrderDetailActivity.this,
                                "通信失败,请检查网络!", 2);
                        finish();
                        break;
                    case Const.STATE_START_QIANG: // 确认取货成功
                        closeDialog();
                        QiangDanData gethdata = (QiangDanData) msg.obj;
                        String qhstatus = gethdata.getStatus();
//                        if (qhstatus != null && qhstatus.equals("1")) {
                        OrderdetailSite site = sitelists.get(getfoodid);
                        site.setStatus("7"); // 已取货,配送中
                        sitelists.set(getfoodid, site);
                        myAdapter.notifyDataSetChanged();
//                        }
                        Common.DisplayToast(OrderDetailActivity.this,
                                gethdata.getMessage(), 2);
                        break;
                    case Const.STATE_START_LOCATION://确认收货
                        closeDialog();
                        QiangDanData qiangDanData = (QiangDanData) msg.obj;
//                        String qhstatus = qiangDanData.getStatus();
//                        if (qhstatus != null && qhstatus.equals("1")) {
                        OrderdetailSite orderdetailSite = sitelists.get(getfoodid);
                        orderdetailSite.setStatus("8"); // 已送达
                        sitelists.set(getfoodid, orderdetailSite);
                        myAdapter.notifyDataSetChanged();
//                        }
                        Common.DisplayToast(OrderDetailActivity.this,
                                qiangDanData.getMessage(), 2);
                        break;
                }
            }
        };

    }

    public void getAdderss(double lat, double lng) {

        GeocodeSearch geocoderSearch = new GeocodeSearch(
                OrderDetailActivity.this);
        geocoderSearch
                .setOnGeocodeSearchListener(new OnGeocodeSearchListener() {

                    @Override
                    public void onGeocodeSearched(GeocodeResult result,
                                                  int rCode) {
                    }

                    @Override
                    public void onRegeocodeSearched(RegeocodeResult result,
                                                    int rCode) {
                        if (result != null
                                && result.getRegeocodeAddress() != null
                                && result.getRegeocodeAddress()
                                .getFormatAddress() != null) {

                            String formatAddress = result.getRegeocodeAddress()
                                    .getFormatAddress();
                            ps_address.setText(formatAddress);

                        } else {
                            ps_address.setVisibility(View.GONE);
                        }
                    }
                });
        LatLonPoint lp = new LatLonPoint(lat, lng);
        RegeocodeQuery query = new RegeocodeQuery(lp, 200, GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);
    }

    public class myAsyncTask extends AsyncTask<String, String, String> {

        private OrderdetailData datas;
        private QiangDanData getfdata; // 确认取货

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            String res = "";
            if (params[0].equals("getdetail")) {
                sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
                String uid = sp.getString("uid", "");
                datas = JsonProcessHelper.jsonProcess_getorderinfo(
                        "get_order_infos", params[1], uid);
                if (null != datas) {
                    res = "getok";
                } else {
                    res = "ping_me_error";
                }

            } else if (params[0].equals("getfood")) { // 确认取货
                sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
                String uid = sp.getString("uid", "");
                getfdata = JsonProcessHelper.jsonProcess_getQsgetfood(
                        "qs_get_food", params[1], uid);
                if (null != getfdata) {
                    res = "getfoodok";
                } else {
                    res = "ping_me_error";
                }
            } else if (params[0].equals("send")) {// 确认收货
                qiangdan = new QiangDanData();
                qiangdan = JsonProcessHelper.jsonProcess_getQsSendFood(
                        "qs_send_food", params[1], params[2]);
                if (qiangdan != null) {
                    res = "state_qiang";
                } else {
                    res = "mi_error";
                }
            }

            return res;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (result.equals("getok")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_SUCCESS;
                msg.obj = datas;
                mHandler.sendMessage(msg);
            } else if (result.equals("ping_me_error")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_ERROR;
                mHandler.sendMessage(msg);
            } else if (result.equals("getfoodok")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_QIANG;
                msg.obj = getfdata;
                mHandler.sendMessage(msg);
            } else if (result.equals("state_qiang")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_LOCATION;
                msg.obj = qiangdan;
                mHandler.sendMessage(msg);
            }
        }

    }

    // 关闭dialog
    void closeDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    // 子订单
    public class ListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return sitelists != null ? sitelists.size() : 0;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            // TODO Auto-generated method stub
            if (sitelists != null) {// 判断软键盘是否已使用
                ViewHolder holder = null;
                if (convertView == null) {
                    convertView = inflater.inflate(R.layout.order_detail_item,
                            null);
                    holder = new ViewHolder();
                    holder.dpname = (TextView) convertView
                            .findViewById(R.id.dpname); // 店铺名称
                    holder.cdlistView = (MyListView) convertView
                            .findViewById(R.id.cdlistView);
                    holder.totalmy = (TextView) convertView
                            .findViewById(R.id.totalmy); // 总金额
                    holder.ordxdtime = (TextView) convertView
                            .findViewById(R.id.ordxdtime); // 下单时间
                    // holder.cdorderid = (TextView) convertView
                    // .findViewById(R.id.cdorderid); // 子订单号
                    // holder.ordpaysta = (TextView) convertView
                    // .findViewById(R.id.ordpaysta); //付款方式

                    holder.callshop = (Button) convertView
                            .findViewById(R.id.callshop); // 联系商家
                    holder.calluser = (Button) convertView
                            .findViewById(R.id.calluser); // 联系顾客
                    holder.ordover = (Button) convertView
                            .findViewById(R.id.ordover); // 完成
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }
                if (convertView != null && sitelists.size() > position) {
                    final OrderdetailSite sitedata = sitelists.get(position);
                    holder.dpname.setText(sitedata.getSite_name());
                    holder.totalmy.setText(sitedata.getFood_amount());
                    holder.ordxdtime.setText(sitedata.getAdd_time());
                    // holder.cdorderid.setText("订单号：" +
                    // sitedata.getOrder_id());
                    // String payvar = "支付宝支付";
                    // String paytype = sitedata.getPaytype();
                    // if(paytype.equals("0")) {
                    // payvar = "货到付款";
                    // } else if (paytype.equals("1") || paytype.equals("3")) {
                    // payvar = "支付宝支付";
                    // } else if(paytype.equals("2")) {
                    // payvar = "微信支付";
                    // }
                    // holder.ordpaysta.setText(payvar);
                    String status = sitedata.getStatus();
                    if (status.equals("7")) { // 已取货,配送中
                        holder.ordover.setText("确认送达");
                        holder.ordover.setBackgroundDrawable(getResources()
                                .getDrawable(R.drawable.orderpsbut));
                    } else if (status.equals("6")) { // 未取货
                        holder.ordover.setText("确认取货");
                        holder.ordover.setBackgroundDrawable(getResources()
                                .getDrawable(R.drawable.orderpsbut));
                    } else {
                        holder.ordover.setBackgroundDrawable(getResources()
                                .getDrawable(R.drawable.order_over));
                        if (status.equals("9")) {
                            holder.ordover.setText("已完成");
                        } else if (status.equals("11")) { // 已取消
                            holder.ordover.setText("已取消");
                        } else if (status.equals("8")) {
                            holder.ordover.setText("已送达");
                        } else if (status.equals("10")) {
                            holder.ordover.setText("已评价");
                        } else if (status.equals("12")) {
                            holder.ordover.setText("待确认");
                        } else if (status.equals("13")) {
                            holder.ordover.setText("商家已接单");
                        }
                    }
                    holder.ordover.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // TODO Auto-generated method stub
                            if (sitedata.getStatus().equals("6")) { // 状态码6+距离店铺距离小于200可以确认取货
                                if (shorterThan200) {
                                    getfoodid = position;
                                    dialog = Common.getTipDialog(
                                            OrderDetailActivity.this,
                                            R.layout.loading, 0, 0);
                                    new myAsyncTask().execute("getfood",
                                            sitedata.getOrder_id());
                                } else {
                                    Toast.makeText(getApplicationContext(), "您当前位置距离店铺较远，无法取货", Toast.LENGTH_SHORT).show();
                                }
                            } else if (sitedata.getStatus().equals("7")) {
                                if (shorterThan200) {
                                    SharedPreferences sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
                                    String empid = sp.getString("uid", "");
                                    if (!empid.equals("") && empid != null) {
                                        if (Common.isNetworkConnected(OrderDetailActivity.this)) {
                                            // mHeaderView.setVisibility(View.VISIBLE);
                                            new myAsyncTask().execute("send", sitedata.getOrder_id(), empid);
                                        } else {
                                            closeProgressDialog();
                                            Common.DisplayToast(OrderDetailActivity.this, "通信失败,请检查网络!", 1);
                                        }
                                    }
                                } else {
                                    Toast.makeText(OrderDetailActivity.this, "您当前位置距离顾客较远，无法点击送达。", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    });

                    holder.callshop.setTag(sitedata.getSite_phone());
                    holder.calluser.setTag(sitedata.getPhone());
                    holder.callshop.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // TODO Auto-generated method stub
                            if (!view.getTag().toString().equals("null")
                                    && !view.getTag().toString().equals("")) {
                                callPhoneNumber(view.getTag().toString());
                            } else {
                                Common.DisplayToast(OrderDetailActivity.this,
                                        "手机号码为空！", 1);
                            }
                        }
                    });
                    holder.calluser.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // TODO Auto-generated method stub

                            if (!view.getTag().toString().equals("null")
                                    && !view.getTag().toString().equals("")) {
                                callPhoneNumber(view.getTag().toString());
                            } else {
                                Common.DisplayToast(OrderDetailActivity.this,
                                        "手机号码为空！", 1);
                            }

                        }
                    });

                    // 将包含listview和店铺商品
                    holder.cdlistView.setAdapter(new ShopdetAdapter(
                            OrderDetailActivity.this, sitedata.getFoodlist()));
                }

            }
            return convertView;
        }
    }

    static class ViewHolder {
        private TextView dpname = null; // 店铺名称
        private MyListView cdlistView = null; // 商品列表
        private TextView totalmy = null; // 总金额
        private TextView ordxdtime = null; // 下单时间
        // private TextView cdorderid = null; // 订单号
        // private TextView ordpaysta = null; //支付方式

        private Button callshop = null; // 联系商家
        private Button calluser = null; // 联系顾客
        private Button ordover = null; // 确认取货
    }

    // 电话
    public void callPhoneNumber(String phoneNumber) {
        if (phoneNumber != null && !phoneNumber.equals("")) {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + phoneNumber));
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            }
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0
                    && Common.isNetworkConnected(OrderDetailActivity.this)) {
                // 定位成功回调信息，设置相关消息
                // amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
//                amapLocation.getLatitude();// 获取纬度
//                amapLocation.getLongitude();// 获取经度
//                amapLocation.getAccuracy();// 获取精度信息
//                if (amapLocation.getLatitude() > 0
//                        && amapLocation.getLongitude() > 0) {
                LatLng lng1 = new LatLng(amapLocation.getLatitude(),
                        amapLocation.getLongitude());
                LatLng lng2 = new LatLng(shopLat, shopLnt);
                float distance = AMapUtils
                        .calculateLineDistance(lng1, lng2);
//                Log.i("yudan", "确认取货distance:" + distance);
                if (distance < 200) {
                    shorterThan200 = true;
                } else {
                    shorterThan200 = false;
                }

//                }
            } else {
                closeProgressDialog();
                Common.DisplayToast(OrderDetailActivity.this, "定位失败,请检查网络!" + amapLocation.getErrorCode(), 1);

            }
        }
    }
}
